package com.rttmall.shopbackend.app.service.impl;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.activation.MimetypesFileTypeMap;

import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.SimplifiedObjectMeta;
import com.rttmall.shopbackend.app.service.OssService;

@Service
public class OssServiceImpl implements OssService, InitializingBean {

	private OSSClient client;
	public static String DEFAULT_CONTENT_TYPE = "application/octet-stream";
	public static MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap();
	// 内网：oss-us-west-1-internal.aliyuncs.com；外网：oss-us-west-1.aliyuncs.com
	@Value("${oss.endPoint}")
	private String endPoint ;
	@Value("${oss.accessKey}")
	private String accessKey ;
	@Value("${oss.accessSecret}")
	private String accessSecret ;
	@Value("${oss.bucketName}")
	private String bucketName ;


	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.println("---------------------------------------"+endPoint);
		this.client = new OSSClient(endPoint, accessKey, accessSecret);
	}
	public void shutDown() {
		client.shutdown();
	}

	public boolean isExist(String key) {
		try {
			boolean found = client.doesObjectExist(bucketName, key);
			return found;
		} catch (OSSException oe) {
		} catch (ClientException ce) {
		}
		return false;
	}

	public void putObject(String key, InputStream inputStream) {
		try {
			ObjectMetadata meta = getMetadata();
			client.putObject(bucketName, key, inputStream, meta);
		} catch (OSSException oe) {
		} catch (ClientException ce) {
		}
	}

	/**
	 * 上传byte[]到OSS
	 * 
	 * @param key
	 * @param bts
	 */
	public void putObject(String key, byte[] bts) {
		try {
			ObjectMetadata meta = getMetadata();
			client.putObject(bucketName, key, new ByteArrayInputStream(bts),
					meta);
		} catch (OSSException oe) {
		} catch (ClientException ce) {
		}
	}

	private ObjectMetadata getMetadata() {
		ObjectMetadata metadata = new ObjectMetadata();
		Date now = new Date();
		Date ExpirationTime = DateUtils.addDays(now, 365);
		metadata.setCacheControl("public, max-age=31536000");
		metadata.setExpirationTime(ExpirationTime);
		return metadata;
	}

	/**
	 * 
	 * 上传文件到OSS
	 * 
	 * @param key
	 * @param file
	 * 
	 */
	public void putObject(String key, File file) {
		try {
			ObjectMetadata meta = getMetadata();
			client.putObject(new PutObjectRequest(bucketName, key, file, meta));
		} catch (OSSException oe) {
		} catch (ClientException ce) {
		}
	}

	/**
	 * 查询Object元数据
	 * 
	 * @param key
	 * @return
	 */
	public SimplifiedObjectMeta getMetadata(String key) {
		try {
			SimplifiedObjectMeta objectMeta = client.getSimplifiedObjectMeta(
					bucketName, key);
			return objectMeta;
		} catch (OSSException oe) {
		} catch (ClientException ce) {
		}
		return null;
	}

	/**
	 * 获取Object
	 * 
	 * @param key
	 * @return
	 */
	public OSSObject getObject(String key) {
		try {
			OSSObject ossObject = client.getObject(bucketName, key);
			return ossObject;
		} catch (OSSException oe) {
		} catch (ClientException ce) {
		}
		return null;
	}

	/**
	 * 删除Object集合
	 * 
	 * @param keys
	 */
	public void deleteObjectList(List<String> keys) {
		try {
			client.deleteObjects(new DeleteObjectsRequest(bucketName)
					.withKeys(keys));
		} catch (OSSException oe) {
			System.out
					.println("Caught an OSSException, which means your request made it to OSS, "
							+ "but was rejected with an error response for some reason.");
			System.out.println("Error Message: " + oe.getErrorCode());
			System.out.println("Error Code:       " + oe.getErrorCode());
			System.out.println("Request ID:      " + oe.getRequestId());
			System.out.println("Host ID:           " + oe.getHostId());
		} catch (ClientException ce) {
			System.out
					.println("Caught an ClientException, which means the client encountered "
							+ "a serious internal problem while trying to communicate with OSS, "
							+ "such as not being able to access the network.");
			System.out.println("Error Message: " + ce.getMessage());
		}
	}

	/**
	 * 创建文件夹
	 * 
	 * @param keySuffixWithSlash
	 */
	public void createFolder(String keySuffixWithSlash) {
		client.putObject(bucketName, keySuffixWithSlash,
				new ByteArrayInputStream(new byte[0]));
	}

	/**
	 * 删除Object
	 * 
	 * @param key
	 */
	public void deleteObject(String key) {
		try {

			client.deleteObject(bucketName, key);
		} catch (OSSException oe) {
		} catch (ClientException ce) {
		}
	}

	public String getContentType(String fileNameOrExt) {
		if (fileNameOrExt == null || fileNameOrExt.isEmpty()) {
			return DEFAULT_CONTENT_TYPE;
		}
		return fileTypeMap.getContentType(fileNameOrExt.toLowerCase());
	}

	public String getUuidName(String name) {
		String uuid = UUID.randomUUID().toString().replaceAll("\\-", "");
		String newName = uuid;
		if (name != null && name.contains(".")) {
			newName = uuid
					+ name.substring(name.lastIndexOf(".")).toLowerCase();
		}
		return newName;
	}


}
